
module Cms
  include DrunkenMaster

  
  class Desktop < Widget

    @@repo = nil

    def index
      desktop = Container.new
      desktop.layout = Layout::Relative.new
      desktop.className += " desktopContainer"
      desktop.draggable = false
      add(desktop)
      
      toolbar = BasicToolbar.new
      desktop.add toolbar
      browser = desktop.add Browser.new
      browser.items.push(*repo.list.collect { |persisted|
        persisted
      })

      toolbar.style(';right:0px; top:0;')
      
      #cmenu = desktop.add ContextMenu.new
      #cmenu.on_create = callback :create
    end

    def self.repo
      unless @@repo
        @@repo = Repository.new
        storage = FileStorage.new
        storage.folder = File.join(File.dirname(__FILE__), 'data')
        @@repo.storage = storage        
      end
      @@repo
    end

    def repo
      Desktop.repo
    end

    def youtube
      add YoutubeFragment.new
    end
    
    def build
      context.page.link_js file_url('jquery-1.3.1.js')
      #context.page.link_js file_url('jquery-ui-personalized-1.6rc6.js')
      #context.page.link_js file_url('jquery.rightClick.js')
      #context.page.link_js 'http://getfirebug.com/releases/lite/1.2/firebug-lite-compressed.js'
      
      context.page.link_js 'http://yui.yahooapis.com/3.0.0pr2/build/yui/yui-min.js'
      
      context.page.link_js file_url('desktop.js')
      context.page.link_js file_url('layout.js')
      context.page.link_js file_url('fragment.js')
      context.page.link_css file_url('desktop.css')
    end
    
    def page
      desktop = Container.new
      desktop.layout = Layout::Relative.new
      desktop.className += " desktopContainer"
      desktop.style = "width:100%; height:100%; margin:0; padding:0; border:none"
      desktop.draggable = false
      add(desktop)
      
      page = desktop.add Page.new
      
      e :script, "
        dcat_instance.oninit(function(Y) {
          var state = Y.get('##{page.id}').get('cat_fragment').getState();
          console.log(state);
          // send to server
          Y.io('#{callback :reconstruct_page}', {
            data : 'state='+escape(Y.JSON.stringify(state)),
            on : {
              complete : function(id, o, args) {
                console.log(o);
                eval(o.responseText);
              }
            }
          });
        })
      "      
    end
    
    def save
      composed = Fragment.compose(context.request.params['state'])
      if uuid = composed.uuid
        repo.put(composed, uuid)
      else
        repo.put(composed)
      end
      respond "
        console.log(\"saved\");
      "
    end

    def delete
      if repo.delete(context.request.params['uuid'])
        respond "OK"
      end
    end

    def open
      composed = repo.get(context.request.params['uuid'])
      rendered = composed.render
      respond "
        jQuery('.desktopContainer').append('#{rendered.join().split("\n").join().split("'").join("\\'")}');
      "
    end
    

    # resizable textarea test
    def textarea
      e :textarea, :id => 'resizeme'
      e :script, 
        "
        dcat_instance.oninit(function(Y) {
          Y.get('#resizeme').on('keydown', function(ev) {
            //console.log(ev);
            var row_height = this.get('clientHeight') / this.get('rows');
            if (ev.charCode == 13 || ev.charCode == 8 || ev.charCode == 46) {
            //if (this.get('scrollHeight') > (this.get('clientHeight') - row_height*1) && !window.opera) {
              this.set('rows', (this.get('scrollHeight') / row_height) + 2);
            //}
            }

            //console.log(this.getStyle('width'));
            //console.log(this.getStyle('fontSize'));
/*
            var row_size = parseInt(this.getStyle('width')) /  parseInt(this.getStyle('fontSize'));
            var rs = this.get('cols');
            if (rs > 0) {
              row_size = rs;
              console.log('row size', rs);
            }
            rows = this.get('value').split(\"\\n\");
            var row_number = rows.length;
            for (var r in rows) {
              if (rows[r].length > row_size) row_number++;
            }
            //console.log(row_number);
            this.set('rows', row_number + 2);
*/
          });
        });
        "
    end

  end
end